// pages/myorder/myorder.js
let app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        primary: app.globalData.primary, // 主题色
        ossPath: app.globalData.ossPath,
        animationData: {}, // 动画
        animationData2: {}, 
        downMenu: false, // 下拉弹框
        orderList: [], // 订单列表
        array: ['全部', '已支付', '代付款', '代生产'],
        menu: { // 筛选
            left: 'state',
            state: 0,
            time: 0,
            timestart: '',// 查询开始时间: default ''
            timeend: '',// 查询结束时间: default ''
            status: '-1', //订单状态 : -1 全部, 0 未支付, 1 支付
            orderCode: '', // 订单号: 全部默认为空
        },
        paging: { // 分页
            pageIndex: 1, // 页码
            pageSize: 10, // 页内条数
            more: true
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //设置主题色
        if (app.globalData.primary) {
            this.setData({ primary: app.globalData.primary })
            app.usePrimary(app.globalData.primary)
        }
    },
    getOrder: function() { // 查询用户订单
        return new Promise(resolve => {
            let timestart = '', timeend = '';
            if (this.data.menu.timestart && this.data.menu.timeend){
                timestart = this.data.menu.timestart + ' 00:00:00'
                timeend = this.data.menu.timeend + ' 00:00:00'
            }
            
            let url = `/orders?status=${this.data.menu.status}&pageIndex=${this.data.paging.pageIndex}&pageSize=${this.data.paging.pageSize}&startTime=${timestart}&endTime=${timeend}&orderCode=${this.data.menu.orderCode}`
            wx.request({
                url: app.globalData.serverPath + url,
                header: app.globalData.header,
                success: function(res) {
                    var data = res.data;
                    try {
                        data = JSON.parse(data)
                    }catch(err) {
                        data = false
                    }
                    resolve(data)
                },
                fail: function(err) {
                    resolve(false)
                }
            })

        })
    },
    filterData: function(data, key) { // 过滤返回数据
        data.forEach(item => {
            item.CreatedDate = item.CreatedDate.replace('T', ' ');
            item.Amount = parseFloat(item.Amount).toFixed(2)
            item[key].forEach(c => {
                c.Amount = parseFloat(c.Amount).toFixed(2)
                var src = '';
                if( c.FilePath.indexOf('.png') > -1) {
                    src = this.data.ossPath + c.FilePath.replace(/^(http|https):\/\/img.alinyin.com/,'')
                } 
                if (!src && c.ThumbnailsUrl) {
                    src = this.data.ossPath + c.ThumbnailsUrl.replace(/^(http|https):\/\/img\.aliyin\.com/, '')
                }
                c.src = src;
            })
        })
        return data
    },
    setDownMenu: function(e) { // 显示下拉选择并动画
        let type = e.currentTarget.dataset.type
        if (type == '-1') return;
        
       this.setAnimation(type);
        
        
    },
    setAnimation: function (type) {//初始化动画
        console.log(type)
        var animation = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease'
        })
        var animation2 = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease'
        })

        if (type) {
            animation.translateY(-404).step()
            animation2.opacity(0).step()
            this.setData({
                downMenu: type,
                animationData: animation.export(),
                animationData2: animation2.export()
            })
            setTimeout(() => {
                animation.translateY(0).step()
                animation2.opacity(1).step()
                this.setData({
                    animationData: animation.export(),
                    animationData2: animation2.export()
                })
            }, 300)

        } else {
            animation.translateY(-404).step()
            animation2.opacity(0).step()
            this.setData({
                animationData: animation.export(),
                animationData2: animation2.export()
            })
            setTimeout(() => {
                this.setData({ downMenu: type })
            }, 300)
        }
    },
    selectMenu: function(e) {
        this.data.menu.left = e.currentTarget.dataset.sel;
        this.setData({
            menu: this.data.menu
        })
    },
    selectMenuState: function(e) { // 选择状态
        this.data.menu.state = e.currentTarget.dataset.state;
        this.setData({
            menu: this.data.menu
        })
    },
    changeTime: function(e) { // 选择开始和结束时间
        this.data.menu.time = e.currentTarget.dataset.time;
        this.setData({
            menu: this.data.menu
        })
    },
    changeTimestart(e) { // 开始时间
        this.data.menu.timestart = e.detail.value
        this.setData({
            menu: this.data.menu
        })
    },
    changeTimeend(e) { // 结束时间
        this.data.menu.timeend = e.detail.value
        this.setData({
            menu: this.data.menu
        })
    },
    gotoDetail(e){ //订单号跳转
        var n = e.currentTarget.dataset.ordernum;
        wx.navigateTo({
            url: '../orderdetail/orderdetail?n=' + n
        })
    },
    handleCancel(e) {  // 取消订单
        var order = e.currentTarget.dataset.order; 
        var index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '确认取消订单吗？',
            success: (res) => {
                if (res.confirm) {
                    let data = `OrderCode=${order}`
                    // console.log('用户点击确定', data)
                    wx.request({
                        url: app.globalData.serverPath + '/Orders',
                        method: 'put',
                        header: app.globalData.header,
                        data: data,
                        success: ({ data }) => {
                            if (data.state == 'ok') {
                                wx.showToast({
                                    title: '取消成功',
                                })
                                this.data.orderList.splice(index, 1)
                                this.setData({
                                    orderList: this.data.orderList
                                })
                            } else {
                                wx.showToast({
                                    title: '取消失败',
                                })
                            }
                        },
                        fail: err => {
                            wx.showToast({
                                title: '取消失败',
                            })
                        }
                    })
                }
            }
        })
    },
    gotoPayment: function(e) { // 去支付
        var orderCode = e.currentTarget.dataset.order;
        wx.navigateTo({
            url: '../payment/index?orderCode=' + orderCode,
        })
    },
    screenOrder: function() { // 筛选订单
        console.log(this.data.menu)
        this.data.paging.pageIndex = 1;
        this.setData({
            paging: this.data.paging
        })
        wx.showLoading({
            title: '加载中',
        })
        this.getOrder().then(data => {
            wx.hideLoading()
            console.log(data.Data)
            data && (() => {
                var res = this.filterData(data.Data, 'OrderItems')
                this.setData({
                    orderList: res
                })
            })()
        })
        this.setAnimation(false)
    },
    getMore: function() {
         if (!this.data.paging.more) return
         this.data.paging.more = false;
         this.setData({
             paging: this.data.paging
         })
        
         this.data.paging.pageIndex++;
         this.getOrder().then(data => {
            
             console.log(data)
             this.data.orderList = [].concat(this.data.orderList, data.Data)
             this.data.paging.more = true;
             this.setData({
                 orderList: this.data.orderList,
                 paging: this.data.paging
             })
         })
        
    },
    reset: function() { //重置
        this.data.paging = {
            pageIndex: 1, // 页码
            pageSize: 10, // 页内条数
            more: true
        }
        this.data.menu = {
            left: 'state',
            state: 0,
            time: 0,
            timestart: '',// 查询开始时间: default ''
            timeend: '',// 查询结束时间: default ''
            status: '-1', //订单状态 : -1 全部, 0 未支付, 1 支付
            orderCode: '', // 订单号: 全部默认为空
        }
        this.setData({
            paging: this.data.paging,
            menu: this.data.menu
        })
        wx.showLoading({
            title: '加载中',
        })
        this.getOrder().then(data => {
            wx.hideLoading()
            console.log(data.Data)
            data && (() => {
                var res = this.filterData(data.Data, 'OrderItems')
                this.setData({
                    orderList: res
                })
            })()
        })
        this.setAnimation(false)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 获取用户订单
        this.getOrder().then(data => {
            console.log(data)
            data && (() => {
                var res = this.filterData(data.Data, 'OrderItems')
                this.setData({
                    orderList: res
                })
            })()
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.getMore();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})